package com.gogowan.agroenterprise.widget;

import it.sauronsoftware.ftp4j.FTPClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gogowan.agroenterprise.OperationActivity;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.contorl.OperationFtpUpload;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.PicturesInfo;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 图片专题的插入图片
 * 
 */
public class OperationPicturesGridView extends ControlView {

	private Context context;
	private GridView gridView;
	private OperationPicturesAdapter adapter;
	private SharedPreferences sharedPreferences;
	private String uploadfile;
	private String newCapturePhotoPath;
	private String dataStr;
	private String name;// 原图
	private String sname;// 缩略
	private String scaledName; // 压缩图
	private int uploadNum; // 上传几个图片标识
	private int system; // 农产品系统和供求系统的分类标识（1为农产品，2为供求系统）
	private BaseActivity operation;
	private Bitmap bitmap = null;
	private FileOutputStream b = null;
	private FileOutputStream zmStream = null;
	private Object ress;
	private File sdDir;
	private String zmfileName;
	private String sfileName;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				PicturesInfo picturesInfo = (PicturesInfo) msg.obj;
				adapter.addPicturesInfo(picturesInfo);
				gridView.setVisibility(View.VISIBLE);

				break;
			default:
				break;
			}
		}

	};

	public OperationPicturesGridView(Context context, String data) {
		super(context, data);
		this.context = context;
		initControl();
		initData();
	}

	public OperationPicturesGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		this.setOrientation(LinearLayout.VERTICAL);
		initControl();
		initData();
	}

	@Override
	public void setData(String newData) {
		super.setData(newData);
	}

	public List<PicturesInfo> getList() {
		return adapter.getDataList();
	}

	public void setList(List<PicturesInfo> list) {
		adapter.setList(list);
	}

	@Override
	public String getData() {
		return null;// IconUtils.imgToStr(bitmap);
	}

	public void clear() {
		adapter.clear();
	}

	public void initData() {
		sharedPreferences = context.getSharedPreferences("LoginINfo", 0);
		String string = sharedPreferences.getString("saveLoginInfo", "");
		LoginResultInfo loginResultInfo = (LoginResultInfo) Utils.fromJSON(
				string, LoginResultInfo.class);
		if (system == 1) {
			uploadfile = loginResultInfo.getFtpfile();
		} else if (system == 2) {
			uploadfile = loginResultInfo.getYxftpfile();
		}
		// uploadfile = loginResultInfo.getFtpfile();
	}

	/**
	 * 初始化控件
	 * 
	 */
	@SuppressWarnings("deprecation")
	public void initControl() {

		final LayoutInflater inflater = LayoutInflater.from(context);
		LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.pictures_grid_view, null);
		this.addView(layout);

		gridView = (GridView) layout.findViewById(R.id.pictures_gride_gv);
		gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		adapter = new OperationPicturesAdapter(context, null, gridView);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				if ((adapter.getCount() - 1) == position) {
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							context);
					builder.setTitle("选择方式");
					builder.setItems(new String[] { "删除" },
							new AlertDialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									boolean isDel = adapter.del(position);
									if (adapter.getCount() <= 1) {
										gridView.setVisibility(View.GONE);
										operation.closePicView();
									} else {
										gridView.setVisibility(View.VISIBLE);
									}

									if (isDel) {
										Toast.makeText(context, "删除图片成功！",
												Toast.LENGTH_SHORT).show();
									} else {
										Toast.makeText(context, "删除图片失败！",
												Toast.LENGTH_SHORT).show();
									}

								}
							});
					builder.show();
				}
			}
		});
	}

	// public void image2SDcard(Intent intent) {
	// File sdDir;
	// String sdStatus = Environment.getExternalStorageState();
	// if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
	// Toast.makeText(context, "无SD卡", Toast.LENGTH_SHORT).show();
	// return;
	// } else {
	// sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
	// }
	//
	// Date date = new Date();
	// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	// File file = new File(sdDir.getPath() + "/AgricultureSystem/Image/");
	// file.mkdirs();// 创建文件夹
	// dataStr = formatter.format(date);
	// newCapturePhotoPath = null;
	//
	// newCapturePhotoPath = sdDir.getPath() + "/AgricultureSystem/Image/"
	// + dataStr + ".jpg";
	//
	// name = newCapturePhotoPath;
	//
	// Uri uri = Uri.fromFile(new File(newCapturePhotoPath));
	// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	// }

	/**
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 * @param uploadNum
	 *            上传几张图片
	 * @param system
	 *            农产品系统和供求系统的分类标识（1为农产品，2为供求系统）
	 */
	public void onViewResult(int requestCode, int resultCode, Intent data,
			int uploadNum, int system, FTPClient ftp, String[] list) {
		BaseActivity base = (BaseActivity) context;
		this.uploadNum = uploadNum;
		this.system = system;
		try {
			if (resultCode == Activity.RESULT_OK) {
				if (requestCode == 0) {// 拍照
					String sdStatus = Environment.getExternalStorageState();
					if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
						Toast.makeText(context, "没有发现SD卡", Toast.LENGTH_SHORT)
								.show();
						return;
					} else {
						sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
					}

					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyyMMddHHmmssSSS");
					String dateStr = dateFormat.format(new Date());

					// 如果第一次上传图片是选择的从内存卡选择文件上传，创建以下两个图片的时候会出现FileNotFoundException
					// 原因：(1)没有创建文件夹，在没有文件夹情况下，创建文件将报错.解决方案为先创建文件夹。
					// (2)有文件夹，但文件所在位置无文件夹，即文件路径太深，超过二级。
					String dir = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N?sdDir.getAbsolutePath():sdDir.getPath()) + "/Image/";
					File directory = new File(dir);
					if (!directory.exists()) {
						directory.mkdirs();
					}
					// 500*500的图
					bitmap = Utils.zoom(newCapturePhotoPath, dir + "/zm"
							+ dateStr + ".jpg", 320);
					if (bitmap == null) {
						Toast.makeText(context, "无法上传此格式文件", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					scaledName = "zm" + dateStr + ".jpg";
					zmfileName = sdDir.getPath()
							+ "/Image/" + sname;
					zmStream = new FileOutputStream(zmfileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, zmStream);// 把数据写入文件
					bitmap.recycle();
					bitmap = null;
					// 小图
					bitmap = Utils.decodeFile(new File(zmfileName), 70);
					sname = "s" + dateStr + ".jpg";
					String sfileName = sdDir.getPath()
							+ "/Image/" + sname;
					b = new FileOutputStream(sfileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
					bitmap.recycle();
					bitmap = null;
					// 填写描述,并上传
					showUploadDialog(newCapturePhotoPath, system, ftp, list);
					base.showView();
				} else if (requestCode == 1) {
					Uri originalUri = data.getData(); // 获得图片的uri
					final String fileName = Utils.getImageAbsolutePath(context,
							originalUri);
					// String[] proj = { MediaStore.Images.Media.DATA,
					// MediaStore.Images.Media.SIZE };
					// ContentResolver resolver = ((Activity) context)
					// .getContentResolver();
					// Cursor cursor = resolver.query(originalUri, proj, null,
					// null, null);
					// // 将光标移至开头 ，这个很重要，不小心很容易引起越界
					// cursor.moveToFirst();
					// final String fileName = cursor
					// .getString(cursor
					// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
					// 填写描述,并上传
					name = fileName;
					String sdStatus = Environment.getExternalStorageState();
					if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
						Toast.makeText(context, "没有发现SD卡", Toast.LENGTH_SHORT)
								.show();
						return;
					} else {
						sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
					}

					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyyMMddHHmmssSSS");
					String dateStr = dateFormat.format(new Date());

					// 如果第一次上传图片是选择的从内存卡选择文件上传，创建以下两个图片的时候会出现FileNotFoundException
					// 原因：(1)没有创建文件夹，在没有文件夹情况下，创建文件将报错.解决方案为先创建文件夹。
					// (2)有文件夹，但文件所在位置无文件夹，即文件路径太深，超过二级。
					String dir = sdDir.getPath() + "/AgricultureSystem/Image";
					File directory = new File(dir);
					if (!directory.exists()) {
						directory.mkdirs();
					}

					// 500*500的图
					bitmap = Utils.zoom(fileName, dir + "/zm" + dateStr
							+ ".jpg", 320);
					if (bitmap == null) {
						Toast.makeText(context, "无法上传此格式文件", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					scaledName = "zm" + dateStr + ".jpg";
					zmfileName = sdDir.getPath()
							+ "/Image/" + sname;
					zmStream = new FileOutputStream(zmfileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, zmStream);// 把数据写入文件
					bitmap.recycle();
					bitmap = null;
					// 小图
					bitmap = Utils.decodeFile(new File(zmfileName), 70);
					sname = "s" + dateStr + ".jpg";
					String sfileName = sdDir.getPath()
							+ "/AgricultureSystem/Image/" + sname;
					b = new FileOutputStream(sfileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
					bitmap.recycle();
					bitmap = null;
					showUploadDialog(fileName, system, ftp, list);
					base.showView();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, "获取图片信息失败", Toast.LENGTH_SHORT).show();
			// MobclickAgent.reportError(context, e);
		}
	}

	public void showUploadDialog(final String fileName, final int system,
			final FTPClient ftp, final String[] list) {

		Log.i("111111111111111111111111111======", fileName);

		// LayoutInflater inflater = LayoutInflater.from(context);
		// View view = inflater.inflate(R.layout.image_dialog, null);
		// final EditText text = (EditText) view
		// .findViewById(R.id.image_dialog_et_message);

		sharedPreferences = context.getSharedPreferences("LoginINfo", 0);
		String string = sharedPreferences.getString("saveLoginInfo", "");
		LoginResultInfo loginResultInfo = (LoginResultInfo) Utils.fromJSON(
				string, LoginResultInfo.class);
		if (system == 1) {
			uploadfile = loginResultInfo.getFtpfile();
		} else if (system == 2) {
			uploadfile = loginResultInfo.getYxftpfile();
		}

		// new AlertDialog.Builder(context) {
		// }.setView(view)
		// // .setCancelable(false)
		// .setPositiveButton("上传", new AlertDialog.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// String message = text.getText().toString();
		try {

			OperationFtpUpload ftpUpload = new OperationFtpUpload(context,
					uploadfile, system, ftp, list);

			UploadImageAsync uploadImageAsync = new UploadImageAsync(ftpUpload,
					"");
			uploadImageAsync.execute(fileName);

		} catch (Exception e) {
			Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			// MobclickAgent.reportError(context, e);
		}
	}

	/**
	 * 保存图片到sd卡
	 * 
	 * @param bitName
	 * @param mBitmap
	 */
	public void saveMyBitmap(String bitName, Bitmap mBitmap) {
		File f = new File("/sdcard/" + bitName + ".png");
		try {
			f.createNewFile();
		} catch (IOException e) {

		}
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			// MobclickAgent.reportError(context, e);
		}
		mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
			// MobclickAgent.reportError(context, e);
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
			// MobclickAgent.reportError(context, e);
		}
	}

	public class UploadImageAsync extends MyAsyncTask {
		private OperationFtpUpload ftpUpload;
		private String description;

		public UploadImageAsync(OperationFtpUpload ftpUpload, String description) {
			this.ftpUpload = ftpUpload;
			this.description = description;
		}

		@Override
		protected Object doInBackground(Object... params) {
			String path = (String) params[0];
			// FileOutputStream b = null;
			// FileOutputStream zmStream = null;
			// Bitmap bitmap = null;
			try {
				// File sdDir;
				// String sdStatus = Environment.getExternalStorageState();
				// if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { //
				// 检测sd是否可用
				// Toast.makeText(context, "没有发现SD卡", Toast.LENGTH_SHORT)
				// .show();
				// return null;
				// } else {
				// sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
				// }
				//
				// SimpleDateFormat dateFormat = new SimpleDateFormat(
				// "yyyyMMddHHmmssSSS");
				// String dateStr = dateFormat.format(new Date());
				//
				// //
				// 如果第一次上传图片是选择的从内存卡选择文件上传，创建以下两个图片的时候会出现FileNotFoundException
				// // 原因：(1)没有创建文件夹，在没有文件夹情况下，创建文件将报错.解决方案为先创建文件夹。
				// // (2)有文件夹，但文件所在位置无文件夹，即文件路径太深，超过二级。
				// String dir = sdDir.getPath() + "/AgricultureSystem/Image";
				// File directory = new File(dir);
				// if (!directory.exists()) {
				// directory.mkdirs();
				// }
				//
				// // 500*500的图
				// bitmap = Utils.zoom(path, dir + "/zm" + dateStr + ".jpg",
				// 320);
				// scaledName = "zm" + dateStr + ".jpg";
				// final String zmfileName = sdDir.getPath()
				// + "/AgricultureSystem/Image/" + scaledName;
				// zmStream = new FileOutputStream(zmfileName);
				// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, zmStream);//
				// 把数据写入文件
				// bitmap.recycle();
				// bitmap = null;
				// // 小图
				// bitmap = Utils.decodeFile(new File(zmfileName), 70);
				// sname = "s" + dateStr + ".jpg";
				// final String sfileName = sdDir.getPath()
				// + "/AgricultureSystem/Image/" + sname;
				// b = new FileOutputStream(sfileName);
				// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);//
				// 把数据写入文件
				// bitmap.recycle();
				// bitmap = null;

				if (uploadNum == 1) {

					try {

						ftpUpload.ftpUpload(zmfileName, "");

						try {
							if (bitmap != null && !bitmap.isRecycled()) {
								// 图片回收
								bitmap.recycle();
								bitmap = null;
							}
							if (b != null) {
								b.flush();
								b.close();
							}
							if (zmStream != null) {
								zmStream.flush();
								zmStream.close();
							}
						} catch (IOException e) {
							Toast.makeText(context, "outputStream close error",
									Toast.LENGTH_SHORT).show();
							e.printStackTrace();
							// MobclickAgent.reportError(context, e);
						} catch (OutOfMemoryError e) {
							Toast.makeText(context, "内存空间不足！",
									Toast.LENGTH_SHORT).show();
							e.printStackTrace();
							// MobclickAgent.reportError(context, e);
						} catch (Throwable e) {
							Toast.makeText(context, "未知异常！", Toast.LENGTH_SHORT)
									.show();
							e.printStackTrace();
							// MobclickAgent.reportError(context, e);
						}
					} catch (Exception e) {
						Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
						// MobclickAgent.reportError(context, e);
					} catch (Throwable e) {
						Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
						// MobclickAgent.reportError(context, e);
					}

				} else if (uploadNum == 2) {
					ftpUpload.ftpUpload(zmfileName, "");
					ftpUpload.ftpUpload(sfileName, "");
				}

				// if (new File(path).exists()) {
				// new File(path).delete();
				// }

				return "1";

			} catch (Exception e) {
				Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				// MobclickAgent.reportError(context, e);
			} catch (OutOfMemoryError e) {
				Toast.makeText(context, "内存空间不足！", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				// MobclickAgent.reportError(context, e);
			} catch (Throwable e) {
				Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				// MobclickAgent.reportError(context, e);
			}
			return null;
		}// 返回json串作为onPostExecute(Object res)的参数 }

		@Override
		protected void onPostExecute(Object res) {
			ress = res;
			Runnable runnable = new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {

						if (!ftpUpload.close()) {
							Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT)
									.show();
							return;
						} else {

							if (!Utils.isEmpty(String.valueOf(ress))) // 上传成功
							{

								PicturesInfo picturesInfo = new PicturesInfo();

								picturesInfo.setUrl(name);
								picturesInfo.setSurl(sname);
								picturesInfo.setPureName(scaledName);
								picturesInfo.setDescription(description);

								android.os.Message msg = new android.os.Message();
								msg.what = 0;
								msg.obj = picturesInfo;
								handler.sendMessage(msg);
							} else { // 未知错误
								Toast.makeText(context, "上传失败",
										Toast.LENGTH_SHORT).show();
							}
						}

					} catch (Exception e) {
						// MobclickAgent.reportError(context, e);
						Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT)
								.show();
					} catch (Throwable e) {
						// MobclickAgent.reportError(context, e);
						Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
					} finally {
						ftpUpload.close();
					}
				}

			};
			new Thread(runnable).start();

			super.onPostExecute(res);
		}
	}

	public void setEnabled(boolean isEnabled) {
		gridView.setEnabled(isEnabled);
	}

	public void setNewCapturePhotoPath(String newCapturePhotoPath) {
		this.newCapturePhotoPath = newCapturePhotoPath;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setLisenter(BaseActivity activity) {
		// activity.closePicView();
		operation = activity;
	}

}